package com.xbongbong.paas.service.stage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.StageProcessEntity;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.model.StageProcessModel;
import com.xbongbong.paas.service.stage.AbstractStageHandleImpl;
import com.xbongbong.paas.service.stage.StageHandle;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.dto.StageSettingScriptDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.entity.CustomerStageEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.CustomerStageModel;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 李少杰
 * @version v1.0.0
 * @date 2021/11/22 19:20
 */
@Service("customerStageHandle")
public class CustomerStageHandle extends AbstractStageHandleImpl implements StageHandle {

    private static final Logger LOG = LoggerFactory.getLogger(CustomerStageHandle.class);
    @Resource
    private CustomerStageModel customerStageModel;
    @Resource
    private StageProcessModel stageProcessModel;


    @Override
    public Integer businessType() {
        return XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode();
    }

    @Override
    public PaasStageEntity getByKey(Long stageId, String corpid) throws XbbException {
        return customerStageModel.getByKey(stageId, corpid);
    }

    @Override
    public List<PaasStageEntity> findEntitys(Map<String, Object> params) {
        List<CustomerStageEntity> entitys = customerStageModel.findEntitys(params);
        return new ArrayList<>(Arrays.asList(entitys.toArray(new PaasStageEntity[0])));
    }

    @Override
    public Integer insert(PaasStageEntity entity) throws XbbException {
        entity.setUpdateTime(DateTimeUtil.getInt());
        entity.setAddTime(DateTimeUtil.getInt());
        return customerStageModel.insert((CustomerStageEntity) entity);
    }

    @Override
    public Integer update(PaasStageEntity entity) throws XbbException {
        entity.setUpdateTime(DateTimeUtil.getInt());
        return customerStageModel.update((CustomerStageEntity) entity);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return customerStageModel.getEntitysCount(param);
    }

    @Override
    public Integer deleteBatch(List<PaasStageEntity> paasStageEntityList, String corpid) {
        return customerStageModel.deleteBatch(beanTransform4List(paasStageEntityList), corpid);
    }

    @Override
    public void insertBatch(List<PaasStageEntity> list) {
        list.forEach(item -> {
            item.setAddTime(DateTimeUtil.getInt());
            item.setUpdateTime(DateTimeUtil.getInt());
        });
        customerStageModel.insertBatch(beanTransform4List(list));
    }

    @Override
    public void insertBatch4Script(List<PaasStageEntity> list) {
        list.forEach(item -> {
            item.setAddTime(DateTimeUtil.getInt());
            item.setUpdateTime(DateTimeUtil.getInt());
        });
        customerStageModel.insertBatch4Script(beanTransform4List(list));
    }

    @Override
    public void updateBatch(List<PaasStageEntity> list, String corpid) {
        list.forEach(item -> item.setUpdateTime(DateTimeUtil.getInt()));
        customerStageModel.updateBatch(beanTransform4List(list), corpid);
    }

    @Override
    public void updateBatchDefaultAndLinkOption(List<PaasStageEntity> list, String corpid) {
        list.forEach(item -> item.setUpdateTime(DateTimeUtil.getInt()));
        customerStageModel.updateBatchDefaultAndLinkOption(beanTransform4List(list), corpid);
    }

    @Override
    public void updateBatch4MirrorRollback(List<PaasStageEntity> list, String corpid) {
        customerStageModel.updateBatch4MirrorRollback(beanTransform4List(list), corpid);
    }

    @Override
    public void updateBatch4Script(List<PaasStageEntity> list) {
        customerStageModel.updateBatch4Script(beanTransform4List(list));
    }

    @Override
    public PaasStageEntity getByCode(String corpid, Long formId, String stageCode) {
        return customerStageModel.getByCode(corpid, formId, stageCode);
    }

    @Override
    public List<ItemPoJo> getStageByStageProgress(Map<String, Object> params, Long formId, String corpid) throws XbbException {
        List<CustomerStageEntity> customerStageEntities = customerStageModel.findEntitys(params);
        if (CollectionsUtil.isEmpty(customerStageEntities)){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return updateStageInfoInExplain(customerStageEntities, formId, corpid);

    }

    @Override
    public void updateStageDefaultAndOption(List<FieldAttrEntity> explains, Long formId, String corpid) throws XbbException {
        List<CustomerStageEntity> updateCustomerStageEntities = new ArrayList<>();
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try {
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(JSONArray.toJSONString(explains));
            FieldAttrEntity fieldAttrEntity = explainMap.get(CustomerManagementEnum.CUSTOMER_STAGE.getAttr());
            if (Objects.isNull(fieldAttrEntity)) {
                return;
            }
            List<ItemPoJo> itemPojos = fieldAttrEntity.getItems();
            if (CollectionsUtil.isEmpty(itemPojos)) {
                return;
            }
            Long stageProcessId;
            if (Objects.equals(fieldAttrEntity.getStageMultiVersion(), 1)) {
                // 开启多版本启用的时候，表单设计页显示的阶段是默认版本的阶段
                stageProcessId = fieldAttrEntity.getDefaultStageProcessId();
                if (Objects.isNull(stageProcessId)) {
                    return;
                }
            } else {
                // 单版本启用的时候，表单设计页显示的阶段是当前启用版本的阶段
                StageProcessEntity stageProcessEntity = stageProcessModel.getEnableStageProcess(corpid, formId);
                if (Objects.isNull(stageProcessEntity)) {
                    return;
                }
                stageProcessId = stageProcessEntity.getId();
            }
            params.put(ParameterConstant.CORPID, corpid);
            params.put(ParameterConstant.FORMID, formId);
            params.put(ParameterConstant.DEL, BasicConstant.ZERO);
            params.put(ParameterConstant.ENABLE, BasicConstant.ONE);
            params.put(ParameterConstant.STAGE_PROCESS_ID, stageProcessId);
            params.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT + " " + SortOrder.DESC);
            List<CustomerStageEntity> customerStageEntities = customerStageModel.findEntitys(params);
            Map<String, CustomerStageEntity> customerStageEntityMap = customerStageEntities.stream().collect(Collectors.toMap(CustomerStageEntity::getCode, Function.identity()));
            for (ItemPoJo item : itemPojos) {
                CustomerStageEntity customerStageEntity = customerStageEntityMap.get(String.valueOf(item.getValue()));
                if (Objects.equals(item.getChecked(),true)) {
                    customerStageEntity.setIsDefault(BasicConstant.ONE);
                } else {
                    customerStageEntity.setIsDefault(BasicConstant.ZERO);
                }
                if (Objects.nonNull(item.getFieldMap())) {
                    customerStageEntity.setLinkOption(JSONArray.parseArray(JSON.toJSONString(item.getFieldMap())));
                } else {
                    customerStageEntity.setLinkOption(null);
                }
                customerStageEntity.setUpdateTime(DateTimeUtil.getInt());
                updateCustomerStageEntities.add(customerStageEntity);
            }
            customerStageModel.updateBatch(updateCustomerStageEntities, corpid);
        } catch (Exception e) {
            LOG.error("CustomerStageHandle.updateStageDefaultAndOption 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 先强转 数据同步后删除次方法
     * @param paasStageEntityList
     * @return
     */
    private List<CustomerStageEntity> beanTransform4List(List<PaasStageEntity> paasStageEntityList) {
        return (List<CustomerStageEntity>)(Object)paasStageEntityList;
    }

}
